<template>
	<view class="content-box">
		<view class="option-box">
			<view class="left">
				
			</view>
			<view class="process">复制链接发送给学生</view>
		</view>
		<view class="detail">
			<view v-for="item in ExamList" style="margin-bottom: 30rpx; border-bottom: 1px solid #777;">
				<view>
					<view style="margin: 60rpx;word-break: break-all;">
						{{item.Url}}
					</view>
					<view style="text-align: center; font-size: var(--text-18);">{{item.StudentStatus}}</view>
				</view>
				<view style="display: flex;justify-content: center;">
					<view style="width: 40%; margin-right: 10px;">
						<u-button style="margin: 30rpx;" @click="copyLink(item)">复制地址</u-button>	
					</view>
					<view style="width: 40%; margin-left: 10px">
						<u-button type="warning" style="margin: 30rpx;" @click="goResult(item)">查看结果</u-button>	
					</view> 
				</view>
				<template v-if="item.IsFinished" >
					<step-student-exam :id="item.ExamId" mode="resp"></step-student-exam>
				</template> 
			</view> 
		</view> 
		<u-button @click="handelNext" class="next-btn w-full" type="warning" :plain="true"><view class="next-text">继续</view></u-button>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted } from 'vue';
	import { useStudyStore } from '@/store/study';
	import { createOptionsMixins, ktlapi } from '@/utils';
	import StepStudentExam from './step-student-exam'
	
	/** 步骤：老师分享测试链接 */
	defineOptions({ name: 'step-link-test', inheritAttrs: false, options: { virtualHost: true } });
	const emit = defineEmits(['module-event']);
	
	const studyStore = useStudyStore();
	//const ExamId = ref('');
	//const LinkUrl = ref("");
	const ExamList = ref([]);
	const StudentStatus = ref("");
	
	function copyLink(item :any){
		console.log(studyStore.LessonUUID)
		// #ifdef H5
		// 浏览器环境
		navigator.clipboard.writeText(item.Url)
		.then(function() {
			uni.showToast({
				title:"复制成功",
				icon:"none"
			})
		  console.log('Text copied to clipboard');
		})
		.catch(function(err) {
		  console.error('Failed to copy text: ', err);
		});
		// #endif
	 
		// #ifdef MP-WEIXIN
		// 微信小程序环境
		wx.setClipboardData({
			data: item.Url,
			success: function () {
				console.log('复制成功');
			}
		});
		// #endif
		
	}
	
	onMounted(()=>{
		uni.showLoading({
			title: '加载中' 
		});
		ktlapi({ 
			action: "Cus_CreateExamLink",
			data: {
				LessonUUID:studyStore.LessonUUID
			}
		}).then((res :any) => {  
			ExamList.value = res.data;
			for(var i=0;i<ExamList.value.length;i++){
				ExamList.value[i]["StudentStatus"] = "等待测试";
				ExamList.value[i]["Url"] = 'https://nx5.abc5g.com/h5/pages-study/study/modules/step-student-exam?ExamId='+ExamList.value[i].ExamId+'&i='+Math.random()
			}
			
			var socketTask = uni.connectSocket({
				url: 'wss://nx5.abc5g.com/apis/WSS/connect', //仅为示例，并非真实接口地址。
				complete: ()=> {
					console.log('WSS已连接'); 
				}
			});
			
			socketTask.onOpen(result=>{
				
				for(var i=0;i<ExamList.value.length;i++){
					
					socketTask.send({
						data:JSON.stringify({
							Action:"ExamConnect",
							Message:JSON.stringify({
								ExamId:ExamList.value[i]["ExamId"],
								Role:"Teacher"
							}),
							Callback:"StudentConnect"
						})
					}); 
				}
				
				
				socketTask.onMessage(result=>{ 
					var json = JSON.parse(result.data);
					console.log(json); 
					if(json["Action"] == "StudentConnect"){
						console.log(JSON.parse(json["Params"]));
						var ExamId = JSON.parse(json["Params"])["ExamId"];
						ExamList.value.filter(x=>{
							return x.ExamId == ExamId;
						})[0]["StudentStatus"] = "学生已经开始测试,请等待结果";
					}
					if(json["Action"] == "ExamFinish"){ 
						console.log(JSON.parse(json["Params"]));
						console.log(ExamList.value);
						var ExamId = JSON.parse(json["Params"])["ExamId"];
						var row = ExamList.value.filter(x=>{
							return x.ExamId == ExamId;
						})[0];
						console.log(row);
						row["StudentStatus"] = "测试结束,结果如下";
						row["IsFinished"] = true;
					}
					if(json["Action"] == "ExamProcess"){ 
						var ExamId = JSON.parse(json["Params"])["ExamId"];
						var row = ExamList.value.filter(x=>{
							return x.ExamId == ExamId;
						})[0];
						console.log(JSON.parse(json["Params"]));
						row["StudentStatus"] = "消除进度:"+JSON.parse(json["Params"])["Msg"];
					}
				})
			}) 
			
			uni.hideLoading(); 
		});  
	})
	
	
	
	function goResult(item){
		uni.showLoading({
			title: '加载中'
		}); 
		ktlapi({ 
			action: "Cus_IsExamFinished",
			data: {
				ID:item.ExamId
			}
		}).then((res :any) => {  
			uni.hideLoading();
			var row = res.data[0]; 
			if(row["IsFinished"]){ 
				item.IsFinished = row["IsFinished"];
			}else{
				uni.showToast({
					title: '尚未完成测试',
					icon: "error",
					duration: 2000
				});
			} 
		});  
	}
	
	const handelNext = () => {
		 
		if(ExamList.value.filter(x=>{
			return !x.IsFinished
		}).length > 0){
			uni.showToast({
				title: '尚未完成测试',
				icon: "error",
				duration: 2000
			}); 
		}else{
			emit('module-event', { action: 'next' });
		}
	}
</script>


<style lang="scss" scoped>
	.content-box{
		--font-color: #332c2b;
		display: flex;
		flex-flow: column;
		flex: 1;
		padding-bottom: 50rpx;
		margin: 0 30rpx;
		
		.option-box {
			display: flex;
			height: 100rpx;
			align-items: center;
		
			.left {
				flex: 1;
				display: flex;
				align-items: center;
		
				.read-text {
					color: #757475;
					margin-right: 20rpx;
					font-size: var(--text-18);
				}
			}
		
			.process {
				padding: 10rpx 14rpx;
				color: #f55f22;
				background-color: #fed7c6;
				border-radius: 30rpx;
				min-width: 150rpx;
				text-align: center;
			}
		}
		
		.detail {
			flex: 1;
			padding-top: 55rpx;
			
		}
	}
	
	.next-text{
		font-size: var(--text-18);
		font-weight: bold;
		display: flex;
	}
	
	/* 针对 1280px 分辨率 */
	@media(min-width:1200px) {
		.content-box {
			width: 2400rpx;
			margin: 0 auto !important;
		}
		
		.process{
			min-width: 238rpx;
		}
	
		.detail {
			
		}
	}
</style>

<style lang="scss" scoped>
	.content-box{
		--font-color: #332c2b;
		display: flex;
		flex-flow: column;
		flex: 1;
		padding-bottom: 50rpx;
		margin: 0 30rpx;
		overflow: auto;
	}
</style>